package controller

import (
	"doctor_api_backend/config"
	"doctor_api_backend/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 获取所有医生
func GetDoctors(c *gin.Context) {
	var doctors []models.Doctor
	config.DB.Find(&doctors)
	c.JSON(200, doctors)
}

// 获取单个医生 by id
func GetDoctorByID(c *gin.Context) {
	id := c.Param("id")
	var doctor models.Doctor
	if err := config.DB.First(&doctor, id).Error; err != nil {
		c.JSON(404, gin.H{"error": "医生不存在"})
		return
	}
	c.JSON(200, doctor)
}

// 创建医生,创建医生不能重复医生联系电话或邮箱,而且邮箱或电话是必传参数
func CreateDoctor(c *gin.Context) {
	var doctor models.Doctor
	if err := c.ShouldBindJSON(&doctor); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	// 检查邮箱或电话是否已存在
	var existingDoctor models.Doctor
	if err := config.DB.Where("contact_phone = ? OR email = ?", doctor.ContactPhone, doctor.Email).First(&existingDoctor).Error; err != nil {
		c.JSON(400, gin.H{"error": "医生联系电话或邮箱已存在"})
		return
	}

	// 创建医生
	config.DB.Create(&doctor)
	c.JSON(201, doctor)
}

// 更新医生
func UpdateDoctor(c *gin.Context) {
	id := c.Param("id")
	var doctor models.Doctor
	if err := config.DB.First(&doctor, id).Error; err != nil {
		c.JSON(404, gin.H{"error": "医生不存在"})
		return
	}

	var updatedDoctor models.Doctor
	if err := c.ShouldBindJSON(&updatedDoctor); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	config.DB.Model(&doctor).Updates(updatedDoctor)
	c.JSON(200, doctor)
}

// 删除医生 by id, 找到doctor_id才删除成功，否者打印删除失败，不存在
func DeleteDoctor(c *gin.Context) {
	id := c.Param("id")
	var doctor models.Doctor
	if err := config.DB.Where("doctor_id = ?", id).First(&doctor).Error; err != nil {
		c.JSON(404, gin.H{"error": "医生不存在"})
		return
	}

	config.DB.Delete(&doctor)
	c.JSON(200, gin.H{"message": "医生删除成功"})
}

// 查询医生病人 通过doctor_id查询医生病人
func GetDoctorPatients(c *gin.Context) {
	doctorID := c.Param("doctorId")
	var patients []models.Patient

	if err := config.DB.Where("doctor_id = ?", doctorID).Find(&patients).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "查询医生病人失败"})
		return
	}
	c.JSON(http.StatusOK, patients)
}

// 查询医生病历记录 通过doctor_id查询医生病历记录
func GetDoctorMedicalRecords(c *gin.Context) {
	doctorID := c.Param("doctorId")
	var records []models.MedicalRecord
	if err := config.DB.Where("doctor_id = ?", doctorID).Find(&records).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "查询医生病历记录失败"})
		return
	}
	c.JSON(http.StatusOK, records)
}
